package com.fbs.wowo.wx.web;

import com.fbs.wowo.exception.DataOverflowException;
import com.fbs.wowo.exception.ErrorCode;
import com.fbs.wowo.wx.entity.WxEntity;
import com.fbs.wowo.wx.mapper.WxEntityMapper;
import com.fbs.wowo.wx.wxUtil.WXBizMsgCrypt;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.annotation.Resource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/")
public class TicketController {
    public static final String encodingAesKey = "MeyUkcRyeofMzTm4nZtCJLnlvizUtYN16T5PVaZX6wg";
    public static final String token = "token";
    public static final String appId = "wx418b64513728dca6";
    public static final String appSecret = "c8fb5d86f8575e7019aa83bb2b20f251";

    @Resource
    private WxEntityMapper wxEntityMapper;

    @PostMapping("/notice")
    @ResponseBody
    public String notice(
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam("msg_signature") String msgSignature,
            @RequestBody String postData) throws Exception {
        WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
        String result2 = pc.decryptMsg(msgSignature, timestamp, nonce, postData);
        System.out.println("decryptMsg:\n"+result2+"\n\n");
        Map<String, String> xmlToMap = xmlToMap(result2);
        if (xmlToMap.get("InfoType").equals("component_verify_ticket")) {
            WxEntity wx = wxEntityMapper.selectByPrimaryKey(1);
            if (wx!=null){
                wx.setTicket(xmlToMap.get("ComponentVerifyTicket"));
                wxEntityMapper.updateByPrimaryKeySelective(wx);
            }
        }
        return "success";
    }


    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<>();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                throw new DataOverflowException(ErrorCode.ERR_NOTICE);
            }
            return data;
        } catch (Exception ex) {
            throw ex;
        }
    }
}
